using System;
using System.IO;
using System.Windows.Forms;
using PddWebAuto.Model;
using PddWebAuto.Properties;

namespace PddWebAuto
{
    public partial class FormNewGroup : Form
    {
        private readonly string _defaultGroupName;
        private readonly bool _editModel;
        public readonly GroupModel GroupInfo;

        public FormNewGroup(GroupModel m)
        {
            if (m == null)
            {
                _editModel = false;
                GroupInfo = new GroupModel();
            }
            else
            {
                GroupInfo = m;
                _editModel = true;
            }

            _defaultGroupName = GroupInfo.Title;
            InitializeComponent();
            DialogResult = DialogResult.None;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var Title = textBox1.Text.Trim();
            if (string.IsNullOrEmpty(Title))
            {
                MessageBox.Show(@"组名称不能为空!");
                return;
            }

            if (!AppClass.CheckName(Title))
            {
                MessageBox.Show(@"组名称内容存在不合法字符!");
                return;
            }

            if (_defaultGroupName != Title)
            {
                if (Directory.Exists(AppClass.GetGroupSubPath(Title)))
                {
                    MessageBox.Show(@"组名称已经存在");
                    return;
                }
            }

            GroupInfo.Title = Title;
            GroupInfo.ProxyUrl = textBox3.Text.Trim();
            GroupInfo.UseProxy = checkBox1.Checked;
            DialogResult = DialogResult.OK;
            Close();
        }

        private void FormNewGroup_Load(object sender, EventArgs e)
        {
            Icon = Resources.a9gw7_5tcr9_001;
            checkBox1.Checked = GroupInfo.UseProxy;
            textBox3.Text = GroupInfo.ProxyUrl;
            textBox1.Text = GroupInfo.Title;
            if (_editModel)
            {
                Text = @"编辑组";
                button1.Text = @"保 存";
            }
            else
            {
                Text = @"新建组";
                button1.Text = @"新 建";
            }
        }
    }
}